package com.chat.common.common.event.Listener;

import com.chat.common.chat.dao.MessageDao;
import com.chat.common.common.event.UserBlackEvent;
import com.chat.common.user.dao.UserDao;
import com.chat.common.user.domain.entity.User;
import com.chat.common.user.service.cache.UserCache;
import com.chat.common.websocket.domain.enums.WSBaseResp;
import com.chat.common.websocket.domain.enums.WSRespTypeEnum;
import com.chat.common.websocket.domain.vo.resp.ws.WSBlack;
import com.chat.common.websocket.service.WebSocketService;
import com.chat.common.websocket.service.adapter.WebSocketAdapter;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.transaction.event.TransactionPhase;
import org.springframework.transaction.event.TransactionalEventListener;

import javax.annotation.Resource;

@Component
public class UserBlackListener {

    @Resource
    private WebSocketService webSocketService;
    @Resource
    private UserDao userDao;

    @Resource
    private UserCache userCache;
    @Resource
    private MessageDao messageDao;

    @Async
    @EventListener(classes = UserBlackEvent.class)
    public void refreshRedis(UserBlackEvent event) {
        userCache.evictBlackMap();
        userCache.remove(event.getUser().getId());
    }

    @Async
    @EventListener(classes = UserBlackEvent.class)
    public void deleteMsg(UserBlackEvent event) {
        messageDao.invalidByUid(event.getUser().getId());
    }

    @Async
    @EventListener(classes = UserBlackEvent.class)
    public void sendPush(UserBlackEvent event) {
        Long uid = event.getUser().getId();
        WSBaseResp<WSBlack> resp = new WSBaseResp<>();
        WSBlack black = new WSBlack(uid);
        resp.setData(black);
        resp.setType(WSRespTypeEnum.BLACK.getType());
        webSocketService.sendToAllOnline(resp, uid);
    }

}
